package cn.edu.hitwh.kanlema.controller;


import cn.edu.hitwh.kanlema.exception.ApiException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.edu.hitwh.kanlema.dto.Result;
import cn.edu.hitwh.kanlema.dto.UserDTO;
import cn.edu.hitwh.kanlema.entity.Blog;
import cn.edu.hitwh.kanlema.entity.User;
import cn.edu.hitwh.kanlema.service.IBlogService;
import cn.edu.hitwh.kanlema.service.IUserService;
import cn.edu.hitwh.kanlema.constant.SystemConstants;
import cn.edu.hitwh.kanlema.util.UserHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author vvcoder
 * @since 2025-8-18
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Resource
    private IBlogService blogService;

    @PostMapping
    public Result saveBlog(@RequestBody Blog blog) {
        return Result.ok(blogService.saveBlog(blog));
    }

    @PutMapping("/like/{id}")
    public Result likeBlog(@PathVariable("id") Long id) {
        // 修改点赞数量
        blogService.likeBlog(id);
        return Result.ok();
    }

    @GetMapping("/of/me")
    public Result queryMyBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @GetMapping("/hot")
    public Result queryHotBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        List<Blog> blogs = blogService.getHotPage(current);
        return Result.ok(blogs);
    }

    @GetMapping("/{id}")
    public Result queryBlogById(@PathVariable("id") Long id) {
        Blog blog = blogService.getBlogById(id);
        return Result.ok(blog);
    }

    @GetMapping("likes/{id}")
    public Result queryBlogLikes(@PathVariable("id") Long id) {
        List<UserDTO> users = blogService.getBlogLikes(id);
        return Result.ok(users);
    }

    @GetMapping("/of/follow")
    public Result queryBlogOfFollow(@RequestParam(value = "lastId", required = false) Long lastId) {
        return Result.ok(blogService.queryBlogOfFollow(lastId));
    }
}
